package com.anjian.bamin.anjiandianzimap.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.PopupMenu;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiton.administrator.shane_library.shane.ZjbBaseActivity;
import com.aiton.administrator.shane_library.shane.app.SysApplication;
import com.aiton.administrator.shane_library.shane.utils.ACache;
import com.aiton.administrator.shane_library.shane.widget.MyProgressDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.anjian.bamin.anjiandianzimap.MyService;
import com.anjian.bamin.anjiandianzimap.R;
import com.anjian.bamin.anjiandianzimap.contant.Constant;
import com.anjian.bamin.anjiandianzimap.model.CompanyInfo;
import com.anjian.bamin.anjiandianzimap.model.CompanyList;
import com.anjian.bamin.anjiandianzimap.utils.MyComparator;
import com.anjian.bamin.anjiandianzimap.widget.ChooseDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MainActivity extends ZjbBaseActivity implements View.OnClickListener {
    private DrawerLayout drawer_layout;
    private ImageView mImg_mine;
    private LinearLayout list_left_drawer;
    MapView mMapView = null;
    private AMap AMap;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    private MyProgressDialog mProgressDialog;
    private String mCityCode;
    private String mCity;
    private String mAmapLocationPoiName;
    private String mAddress;
    private LatLng mLocationLatLng;
    private List<CompanyInfo> mCompanyInfoList = new ArrayList<>();
    private int chooseMode = 3;

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    double latitude = amapLocation.getLatitude();//获取纬度
                    double longitude = amapLocation.getLongitude();//获取经度
                    if (mProgressDialog != null && mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();//定位后取消progressDialog
                        mProgressDialog = null;
                    }
                    mCityCode = amapLocation.getCityCode();
                    mCity = amapLocation.getCity();
                    //设置上车地址
                    mAmapLocationPoiName = amapLocation.getPoiName();
                    mAddress = amapLocation.getAddress();
                    mLocationLatLng = new LatLng(latitude, longitude);
                    if (mCompanyListAcacheAsObject == null) {
                        for (int i = 0; i < 20; i++) {
                            mCompanyInfoList.add(new CompanyInfo("艾通"+i, "AT", "禾山路", "15871105320", 24.506535+i*0.001, 118.135506+i*0.001));
                            mCompanyInfoList.add(new CompanyInfo("好利用机械设备有限公司"+i, "HLYJXSBYXGS", "福建省泉州市鲤城区新年南路菜州溪滨巷2号", "13328526669", latitude + 0.004*i, longitude - 0.003*i));
                            mCompanyInfoList.add(new CompanyInfo("久久液压气动配件有限公司"+i, "JJYYQDPJYXGS", "泉州市鲤城区江滨北路滨江花园城B区9号店", "15879653652", latitude - 0.003*i, longitude + 0.003*i));
                            mCompanyInfoList.add(new CompanyInfo("金锦机电设备有限公司"+i, "JJJDSBYXGS", "泉州市鲤城区金龙街道南环路589号三楼", "13659752658", latitude - 0.005*i, longitude + 0.002*i));
                            mCompanyInfoList.add(new CompanyInfo("中科达机械设备有限公司"+i, "ZKDJXSBYXGS", "福建省泉州市鲤城区", "15876552652", latitude + 0.002*i, longitude + 0.003*i));
                        }
                        Collections.sort(mCompanyInfoList,new MyComparator());
                        mCompanyListAcache.put(Constant.ACACHE.COMPANY_LIST, new CompanyList(mCompanyInfoList));

                    }
                    moveCenterMarker(mLocationLatLng);
                    initMarker();
                    Log.e("onLocationChanged ", "onLocationChanged 定位坐标" + mLocationLatLng.toString());
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }

    };


    /**
     * a-z排序
     */
    private class CityComparator implements Comparator<CompanyInfo>{
        @Override
        public int compare(CompanyInfo lhs, CompanyInfo rhs) {
            String a = lhs.getCompanyPinyin().substring(0, 1);
            String b = rhs.getCompanyPinyin().substring(0, 1);
            return a.compareTo(b);
        }
    }

    private ArrayList<Marker> mMarkers;
    private ACache mCompanyListAcache;
    private CompanyList mCompanyListAcacheAsObject;

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMyBind = (MyService.MyBind) service;
//            mMyBind.XunCha();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    private MyService.MyBind mMyBind;
    private ImageView mImageSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initMap(savedInstanceState);
    }

    private void initMarker() {
        ArrayList<MarkerOptions> arrayMarkrOption = new ArrayList<>();
        arrayMarkrOption.clear();
        for (int i = 0; i < mCompanyInfoList.size(); i++) {
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.title("" + i);
            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.b_poi));
            markerOptions.position(new LatLng(mCompanyInfoList.get(i).getCompanyLat(), mCompanyInfoList.get(i).getCompanyLng()));
            arrayMarkrOption.add(markerOptions);
        }
        mMarkers = AMap.addMarkers(arrayMarkrOption, false);
    }

    private void initMap(Bundle savedInstanceState) {
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mMapView.onCreate(savedInstanceState);
        AMap = mMapView.getMap();
        //设置默认定位按钮是否显示
        UiSettings uiSettings = AMap.getUiSettings();
        uiSettings.setMyLocationButtonEnabled(false);
        uiSettings.setZoomControlsEnabled(false);
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        AMap.setMyLocationEnabled(true);
        AMap.moveCamera(CameraUpdateFactory.zoomBy(6));
        AMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                View inflate = getLayoutInflater().inflate(R.layout.companymarker, null);
                TextView textView_companyName = (TextView) inflate.findViewById(R.id.textView_companyName);
                int title = Integer.parseInt(marker.getTitle());
                textView_companyName.setText(mCompanyInfoList.get(title).getCompanyName());
                return inflate;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });
        AMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
//                LatLng position = AMap.getCameraPosition().target;
//                Log.e("onTouch ", "onTouch 中心点坐标"+position.toString());
            }
        });
        AMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                for (int i = 0; i < mMarkers.size(); i++) {
                    Marker marker = mMarkers.get(i);
                    if (marker.isInfoWindowShown()) {
                        marker.hideInfoWindow();
                    }
                }
            }
        });
        AMap.setOnInfoWindowClickListener(new AMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                int title = Integer.parseInt(marker.getTitle());
                Intent intent = new Intent();
                intent.putExtra("companyInfo", mCompanyInfoList.get(title));
                intent.setClass(MainActivity.this, CompanyDetialActivity.class);
                startActivityTo(intent);
            }
        });
        AMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                marker.showInfoWindow();
                return true;
            }
        });
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        mCompanyListAcache = ACache.get(MainActivity.this, Constant.ACACHE.COMPANY_LIST_ACACHE);
        mCompanyListAcacheAsObject = (CompanyList) mCompanyListAcache.getAsObject(Constant.ACACHE.COMPANY_LIST);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void findID() {
        drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
        list_left_drawer = (LinearLayout) findViewById(R.id.list_left_drawer);
        mImg_mine = (ImageView) findViewById(R.id.imageView_mine);
        mMapView = (MapView) findViewById(R.id.map);
        mImageSearch = (ImageView) findViewById(R.id.imageSearch);

    }

    @Override
    protected void initViews() {
        setProgressDialog("正在定位……");
    }

    @Override
    protected void setListeners() {
        mImg_mine.setOnClickListener(this);
        mImageSearch.setOnClickListener(this);
        findViewById(R.id.rela_all_order).setOnClickListener(this);
        findViewById(R.id.imageView_reLocation).setOnClickListener(this);
        findViewById(R.id.rela_xuncha_list).setOnClickListener(this);


    }

    @Override
    protected void onStart() {
        super.onStart();
        ACache aCacheCompanyList = ACache.get(MainActivity.this, Constant.ACACHE.COMPANY_LIST_ACACHE);
        if (aCacheCompanyList != null) {
            CompanyList companyList = (CompanyList) aCacheCompanyList.getAsObject(Constant.ACACHE.COMPANY_LIST);
            if (companyList != null) {
                mCompanyInfoList.clear();
                List<CompanyInfo> companyInfoList = companyList.getCompanyInfoList();
                mCompanyInfoList.addAll(companyInfoList);
            }
        }
        //启动定位
        mLocationClient.startLocation();
        Intent server = new Intent();
//        server.putExtra("companyList",new CompanyList(mCompanyInfoList));
        server.setClass(MainActivity.this, MyService.class);
        bindService(server, conn, Context.BIND_AUTO_CREATE);
        startService(server);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.rela_xuncha_list:
                intent.setClass(MainActivity.this, XunChaListActivity.class);
                startActivityTo(intent);
                break;
            case R.id.rela_all_order:
                intent.setClass(MainActivity.this, CompanyListActivity.class);
                startActivityTo(intent);
                break;
            case R.id.imageView_mine:
                drawer_layout.openDrawer(list_left_drawer);
                break;
            case R.id.imageSearch:

                showPopupMenu(mImageSearch);
                break;
            case R.id.imageView_reLocation:
                mLocationClient.startLocation();
                Log.e("MainActivity", "onClick: --->>定位");

                break;
        }
    }

    private void showPopupMenu(View view) {
        // View当前PopupMenu显示的相对View的位置
        PopupMenu popupMenu = new PopupMenu(this, view);
        // menu布局
        popupMenu.getMenuInflater().inflate(R.menu.menu_main, popupMenu.getMenu());
        // menu的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_choose:
                        ChooseDialog chooseDialog = new ChooseDialog(MainActivity.this,chooseMode,true);

                        chooseDialog.show();
                        chooseDialog.setOnBtnClickListener(new ChooseDialog.OnBtnClickListener() {
                            @Override
                            public void onCompanyClick(int companyInfo) {
                                Log.e("MainActivity", "onCompanyClick: --->>" +companyInfo );
                                chooseMode = companyInfo;
                            }
                        });
                        break;
                    case R.id.menu_search:
                        startActivityTo(new Intent(MainActivity.this, SearchActivity.class));
                        break;
                }
                return false;
            }
        });

        popupMenu.show();
    }


    @Override
    protected void onStop() {
        mLocationClient.stopLocation();//停止定位
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        mLocationClient.onDestroy();//销毁定位客户端。
        unbindService(conn);
        super.onDestroy();

    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }

    private void setProgressDialog(String text) {
        if (mProgressDialog == null) {
            mProgressDialog = new MyProgressDialog(this, text);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                        mProgressDialog.dismiss();
                        SysApplication.getInstance().exit();
                    }
                    return false;
                }
            });
        } else {

        }
    }

    private void moveCenterMarker(LatLng latLng) {
        AMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
    }

    /**
     * 分级
     */
//    public class ChooseDialog extends Dialog {
//        private Context context;
//        private RadioGroup mRadioGroup;
//
//        public ChooseDialog(Context context) {
//            super(context, R.style.dialog);
//            this.context = context;
//        }
//
//        @Override
//        protected void onCreate(Bundle savedInstanceState) {
//            super.onCreate(savedInstanceState);
//            LayoutInflater inflater = LayoutInflater.from(context);
//            View view = inflater.inflate(R.layout.dialog_choose, null);
//            setContentView(view);
//            Button mBtnSure = (Button) view.findViewById(R.id.btn_sure);
//            mRadioGroup = (RadioGroup) view.findViewById(R.id.radio_group);
//            RadioButton mRadioAll = (RadioButton) view.findViewById(R.id.radio_all);
//            RadioButton mRadioOne = (RadioButton) view.findViewById(R.id.radio_one);
//            RadioButton mRadioTwo = (RadioButton) view.findViewById(R.id.radio_two);
//            RadioButton mRadioThree = (RadioButton) view.findViewById(R.id.radio_three);
//
//            switch (chooseMode) {
//                case 0:
//                    mRadioAll.setChecked(true);
//                    break;
//                case 1:
//                    mRadioOne.setChecked(true);
//                    break;
//                case 2:
//                    mRadioTwo.setChecked(true);
//                    break;
//                case 3:
//                    mRadioThree.setChecked(true);
//                    break;
//
//            }
//
//
//            mBtnSure.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    int checkedRadioButtonId = mRadioGroup.getCheckedRadioButtonId();
//                    for (int i = 0; i < radioButtons.length; i++) {
//                        if (radioButtons[i] == checkedRadioButtonId) chooseMode = i;
//                    }
//                    dismiss();
//                }
//            });
//
//            Window dialogWindow = getWindow();
//            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//            DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高用
//            lp.width = (int) (d.widthPixels * 0.6); // 高度设置为屏幕的0.6
//            dialogWindow.setAttributes(lp);
//        }
//
//    }
}
